package cfengMiddleware.server.springEventDriven.producer;

import cfengMiddleware.server.springEventDriven.event.LoginEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author Cfeng
 * @date 2022/9/15
 * 事件发送者的生产者
 */

@Component
@Slf4j
public class Producer {

    //消息发送组件Publisher,自动配置的
    @Resource
    private ApplicationEventPublisher publisher;

    //发送消息
    public void sendMessage(String userName, String ip) throws Exception {
        //消息实体
        LoginEvent event = new LoginEvent(this, userName,new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()),ip);
        //发送消息，触发事件
        publisher.publishEvent(event);
        log.info("spring消息驱动 生产者发送消息 ： {}",event);
    }
}
